<template>
  <div class="app-container">
    <el-row class="header">
      <el-button type="primary" :icon="RefreshRight"
      @click="initMenuList()">刷新</el-button>
      <el-button type="success" :icon="DocumentAdd"
      @click="handleDialogValue()">新增</el-button>
    </el-row>
    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      stripe
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      
      <el-table-column prop="name" label="菜单名称" width="220"/>
      <el-table-column prop="icon" label="图标" width="60" align="center">
        <template v-slot="scope">
          <el-icon>
            <svg-icon :icon="scope.row.icon"/>
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="order_num" label="排序" width="60" align="center"/>
      <!-- <el-table-column prop="api_path" label="API路径" width="200"/> -->
      <el-table-column prop="api_path" label="API路径">
        <template v-slot="scope">
          <div v-if="scope.row.api_path && scope.row.api_path.length > 0"> 
            <div v-for="(path, index) in getApiPaths(scope.row.api_path)" :key="index" class="mb-1">
              <el-tag 
                type="success" 
                effect="plain" 
                size="small" 
                class="mr-1"
                :style="{cursor: 'pointer'}"
              >
                {{ path }}
              </el-tag>
            </div>
          </div>
          <div v-else>
            <el-tag type="info" effect="plain" size="small">未设置</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="path" label="组件路径" width="180"/>
      <el-table-column prop="perms" label="权限标识" width="100"/>
      <el-table-column prop="menu_type" label="菜单类型" width="100" align="center">
        <template v-slot="scope">
          <el-tag size="small" v-if="scope.row.menu_type === 'M'" 
          type="danger" effect="dark">目录</el-tag>
          <el-tag size="small" v-else-if="scope.row.menu_type === 'C'"
          type="success" effect="dark">菜单</el-tag>
          <el-tag size="small" v-else-if="scope.row.menu_type === 'F'" 
          type="info" effect="dark">按钮</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" align="center"/>
      <el-table-column prop="action" label="操作" width="200" fixed="right" align="center">
        <template v-slot="scope">
          <el-button type="primary" :icon="Edit" @click="handleDialogValue(scope.row.id)"/>
          <el-popconfirm title="您确定要删除这条记录吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" :icon="Delete"/>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <Dialog v-model="dialogVisible" :tableData="tableData" :dialogVisible="dialogVisible" :id="id" :dialogTitle="dialogTitle" @initMenuList="initMenuList"></Dialog>
  </div>
  </template>

<script setup>
import {Search, Delete, DocumentAdd, Edit, Tools, RefreshRight} from '@element-plus/icons-vue'
import {ref} from 'vue'
import requestUtil, {getServerUrl} from "@/util/request";
import Dialog from './components/dialog.vue'
import {ElMessage, ElMessageBox} from 'element-plus'

const tableData = ref([])
const initMenuList = async () => {
  try {
    const res = await requestUtil.get('system/menu_tree');
    tableData.value = res.menu_tree;
  } catch (error) {
    console.error('获取菜单列表失败', error)
    ElMessage.error('获取菜单列表失败')
  }
}

initMenuList();

const id = ref(-1)
const dialogVisible = ref(false)
const dialogTitle = ref('')

const handleDialogValue = (menuId) => { 
  if (menuId) {
    id.value = menuId;
    dialogTitle.value = "菜单编辑"
  }else {
    id.value = -1;
    dialogTitle.value = "菜单添加"
  }
  dialogVisible.value = true
}


const handleDelete = async (menuId) => {
  try {
    await requestUtil.del("system/menu/" + menuId + "/");
    ElMessage.success("删除成功");
    initMenuList();
  } catch (error) {
    console.log(error)
    ElMessage.error("删除失败");
  }
}

// 解析API路径
const getApiPaths = (apiPath) => {
  if (!apiPath) return []
  
  // 如果是字符串形式的数组，尝试解析
  if (typeof apiPath === 'string') {
    try {
      // 移除可能存在的引号和方括号
      const cleanPath = apiPath.replace(/^\[|\]$/g, '').replace(/"/g, '').replace(/'/g, '')
      
      // 如果是空字符串，返回空数组
      if (!cleanPath.trim()) return []
      
      // 按逗号分割
      return cleanPath.split(',').map(item => item.trim())
    } catch (e) {
      console.error('解析API路径失败:', e)
      return [apiPath] // 解析失败时返回原始字符串
    }
  }
  
  // 如果已经是数组，直接返回
  if (Array.isArray(apiPath)) {
    return apiPath
  }
  
  // 其他情况，返回包含原始值的数组
  return [apiPath]
}

</script>

<style lang="scss" scoped>

.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}
.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}
::v-deep th.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 13px;
}
.el-tag--small {
  margin-left: 5px;
}
</style>
